//
//  HomeController.m
//  SNS
//
//  Created by Bobo on 11-11-29.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "HomeController.h"
#import "SendController.h"
#import "PopUpView.h"
#import "MsgCell.h"
#import "CoreDataManager.h"
#import "UserInfo.h"
#import "Msg.h"
#import "SettingController.h"

@interface HomeController (Private) 

- (void)removePopUpView;

@end

@implementation HomeController

@synthesize popUpView;
@synthesize msgDatas;

- (void)dealloc {
    [popUpView release];
    [msgDatas release];
    
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    self.tableView.dataSource = self;
//    self.tableView.delegate = self;
    
    self.title = @"信息流";

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] 
                                              initWithBarButtonSystemItem:UIBarButtonSystemItemCompose
                                              target:self
                                              action:@selector(goToSendController)] autorelease];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] 
                                               initWithImage:[UIImage imageNamed:@"light.png"]
                                               style:UIBarButtonItemStylePlain
                                               target:self
                                               action:@selector(showPopUpView)] autorelease];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(clearMsg)
                                                 name:kNotificationClearMsgHistory
                                               object:nil];
    
    [self reloadData];
}

- (void)reloadData {
    self.msgDatas = [NSMutableArray array];
    NSArray *msgs = [[CoreDataManager sharedManager] getAllObjectOfClass:[Msg class]
                                                                 orderBy:@"time"
                                                               ascending:NO];
    [self.msgDatas addObjectsFromArray:msgs];
    
    [self.tableView reloadData];
}

- (void)clearMsg {
    [self.msgDatas removeAllObjects];
    [self.tableView reloadData];
}

- (void) goToSendController {
    SendController *sendController = [[[SendController alloc] init] autorelease];
    sendController.homeController = self;
//    UINavigationController *navigationController = [[[UINavigationController alloc] initWithRootViewController:sendController] autorelease];
//    navigationController.navigationBar.barStyle = UIBarStyleBlack;
//    [self presentModalViewController:navigationController animated:YES];
    [self.navigationController pushViewController:sendController animated:YES];
}

- (void) showPopUpView {
    if (self.popUpView == nil) {
        UIControl *control = [[[UIControl alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
        [[UIApplication sharedApplication].keyWindow addSubview:control];
        [control addTarget:self action:@selector(removePopUpView) forControlEvents:UIControlEventTouchDown];
        
        self.popUpView = [[[PopUpView alloc] initWithFrame:CGRectMake(5, 64, 150, 60)] autorelease];
        [control addSubview:self.popUpView];
        self.popUpView.homeController = self;
    }
    else {
        [self removePopUpView];
    }
}

- (void)removePopUpView {
    UIView *control = self.popUpView.superview;
    [control removeFromSuperview];
    self.popUpView = nil;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.msgDatas count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MsgCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[MsgCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    UserInfo *userInfo = (UserInfo *)[[CoreDataManager sharedManager] getObjectOfClass:[UserInfo class]];
    
    ((MsgCell *)cell).name.text = userInfo.name;
    
    Msg *msgData = [self.msgDatas objectAtIndex:[indexPath row]];
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    ((MsgCell *)cell).time.text = [dateFormatter stringFromDate:msgData.time];
    ((MsgCell *)cell).msg.text = msgData.msg;
    
    if (msgData.imageID != nil) {
        NSString *imagePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@", msgData.imageID];
        ((MsgCell *)cell).image.image = [UIImage imageWithContentsOfFile:imagePath];
    }
    
    NSString *avatarFilePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/avatar"];
    ((MsgCell *)cell).avatar.image = [UIImage imageWithContentsOfFile:avatarFilePath];
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    float avatarHeight = 50;
    float minHeight = 10 + avatarHeight + 10;
    
    Msg *msgData = [self.msgDatas objectAtIndex:[indexPath row]];
    NSString *text = msgData.msg;
    
    CGSize msgSize = [text sizeWithFont:[UIFont systemFontOfSize:14]
                      constrainedToSize:CGSizeMake(240, MAXFLOAT)];
    float msgHeight = msgSize.height;
    float nameHeight = 20;
    
    float imageHeight;
    if (msgData.imageID != nil) {
        NSString *imagePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@", msgData.imageID];
        UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
        imageHeight = image.size.height;
    }
    
    float height = 10 + nameHeight + 10 + msgHeight + 10;
    
    return MAX(minHeight, height);
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}

@end
